

<template>
  <div class="userDetails">
    <div class="crumbs">
      <header class="crumbs_arr_box">
        <span @click="routerChange('/dataAnalysis/userIndex/userGroup',{})">用户分群</span>
        <span>
          <i class="el-icon-arrow-right"></i>
        </span>
        <span>分群详情</span>
      </header>
    </div>
    <header class="panelHeader card_table">
      <div class="flex_btw">
        <span class="head">
          {{activeDetails.cname}}
          <i class="el-icon-document"></i>
        </span>
        <span>
          <span class="txt">
            <i class="el-icon-thumb" v-if="activeDetails.isRoutine==0"></i>
            <i class="el-icon-sort" v-if="activeDetails.isRoutine==1"></i>
            {{isRoutineSwitch(activeDetails.isRoutine)}}更新
          </span>
          <span class="txt">
            <i class="el-icon-user"></i>
            {{activeDetails.creatorName}}
          </span>
          <span class="txt">{{activeDetails.createTime?time_change(activeDetails.createTime):'未知'}}</span>
          <span class="txt">{{sourceTypeSwitch(activeDetails.sourceType)}}</span>
        </span>
      </div>
      <div class="flex_btw">
        <span class="run flex_btw">
          <i v-if="activeDetails.runningStatus==0" class="info el-icon-loading"></i>
          <i v-if="activeDetails.runningStatus==1" class="green el-icon-finished"></i>
          <i v-if="activeDetails.runningStatus==3" class="err el-icon-video-play"></i>
          <i v-if="activeDetails.runningStatus==10" class="green el-icon-video-pause"></i>
          {{runningStatusShow(activeDetails.runningStatus)}}
        </span>
        <span></span>
      </div>
      <div class="flex_btw">
        <span class="circle">
          <span class="headCir" @click="routerChange('/userSelf',{})">
            {{activeDetails.userCount?activeDetails.userCount:'0'}}
            <i>人</i>
            <i :class="activeDetails.computeStatus==10?'point pointgreen':'point pointerr'"></i>
            <span class="txt">{{time_change(activeDetails.finishedTime)}}</span>
            <i class="el-icon-arrow-right"></i>
          </span>
        </span>
        <span>
          <el-button size="small" :disabled="queryStatus"  @click="createRules" plain>查看规则</el-button>
          <el-button size="small" plain>...</el-button>
        </span>
      </div>
    </header>
    <section class="card_table">
      <div class="flex_btw">
        <span>分群历史详情</span>
        <span>
          <el-date-picker
            @change="pageInfo.currentPage=1;queryHistory();"
            size="small"
            v-model="time"
            :clearable="false"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </span>
      </div>
      <div v-loading="tableLoading" id="userDetailsEchart"></div>
    </section>
    <footer class="card_table">
      <el-table v-loading="tableLoading" :data="activeDetailsHistory" style="width: 100%">
        <el-table-column prop="startTime" width="240" :show-overflow-tooltip="true" label="计算基准时间">
          <template slot-scope="scope">
            <div class="tanleOne">
              <i class="el-icon-time"></i>
              {{time_change(scope.row.baseTime)}}
            </div>
          </template>
        </el-table-column>
        <el-table-column width="240" prop="userCount" label="分群人数">
          <template slot-scope="scope">
            <div class="tanleOne">
              <i class="el-icon-user"></i>
              {{scope.row.userCount}}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="计算详情">
          <template slot-scope="scope">
            <div class="tanleOne flex_sta">
              <span class="block">
                <i :class="classChoose(scope.row.status)"></i>
                {{statusSwitch(scope.row.status)}}
              </span>
              <span class="time">{{time_change(scope.row.finishedTime)}}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" v-if="$currentRole>2" width="100" label="操作">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="重新计算结果" placement="top">
              <el-button plain size="mini" @click="userGroupHistoryUpdateGet(scope.row)" type="text">
                <i class="el-icon-refresh bigIcon"></i>
              </el-button>
            </el-tooltip>
            <!-- <el-tooltip class="item" effect="dark" content="下载" placement="left">
              <el-button plain size="mini" type="text">
                <i class="el-icon-download bigIcon"></i>
              </el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>
      <div class="pageBox flex_cen">
        <el-pagination
          :current-page="pageInfo.currentPage"
          @size-change="handleSizeChange"
          @current-change="currentChange"
          :page-sizes="[5, 10, 50]"
          :page-size="pageInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total"
        ></el-pagination>
      </div>
    </footer>
    <createRules :disabledType="true" @update="updateChange" :update="true" :item="activeItem" ref="createdRules"></createRules>
  </div>
</template>

<script>
import createRules from "./createRules.vue";
import ElementResize from "@/utils/ElementResize.js";
export default {
  name: "userDetails", // 用户分群
  watch: {},
  data() {
    return {
      queryStatus:true,
      id: null, // 路径传过来的id查询关键字
      pageInfo: {
        total: 79,
        currentPage: 1,
        pageSize: 5
      },
      time: [], // 分群历史详情   时间  入参
      activeItem: {},
      activeDetails: {}, // 分群详情
      activeDetailsHistory: [], // 分群历史详情
      tableData: [], // 存储的全部表格数据
      myChart: null,
      tableLoading: false
    };
  },
  methods: {
    async updateChange(obj){
      let _res = await this.$analysisApi.userAnalysis.userGroupUpdate(obj);
      if (_res&&_res.success) {
        this.$message({
          message: "修改成功",
          type: "success"
        });
        this.activeItem = obj;
        this.query(); // 查询分群详情
        this.queryHistory(); // 查询历史详情
      }
    }, // 规则更改函数
    runningStatusShow(runningStatus) {
      let res = "未知";
      switch (runningStatus) {
        case 0:
          res = "待执行";
          break;
        case 1:
          res = "已完成";
          break;
        case 2:
          res = "已删除";
          break;
        case 3:
          res = "已暂停";
          break;
        case 10:
          res = "运行中";
          break;
      }
      return res;
    }, // 运行状态枚举
    async query() {
      this.queryStatus = true;
      let _res = await this.$analysisApi.userAnalysis.userGroupQuery({
        id: this.id
      });
      if (_res&&_res.success) {
        this.queryStatus = false;
        this.activeDetails = _res.value;
      }
    }, // 分群详情查询
    async queryHistory() {
      this.tableLoading = true;

      let _res = await this.$analysisApi.userAnalysis.userGroupHistory({
        userGroupId: this.id,
        startTime: this.time[0]?this.time[0]:null,
        endTime: this.time[1]?this.time[1]:null
      });
      this.tableLoading = false;
      if (_res&&_res.success) {
        this.pageInfo.total = _res.value.total;
        _res.value.list.reverse();
        this.tableData = JSON.parse(JSON.stringify(_res.value.list)); // 存储全部历史详情数据
        this.activeDetailsHistory = this.pageHandle(
          this.tableData,
          this.pageInfo.currentPage,
          this.pageInfo.pageSize
        );
        this.echartInit();
      }
    }, // 历史详情查询
    async userGroupHistoryUpdateGet(item){
      this.tableLoading = true;
      let _res = await this.$analysisApi.userAnalysis.userGroupHistoryUpdate({
        id: item.id,
      });
      this.tableLoading = false;
      if (_res&&_res.success) {
        this.queryHistory(); // 重新查询历史详情
      }
    },// 历史详情查询刷新  重新计算
    handleSizeChange(v) {
      this.pageInfo.pageSize = v;
      this.activeDetailsHistory = this.pageHandle(
        this.tableData,
        this.pageInfo.currentPage,
        this.pageInfo.pageSize
      );
    },
    currentChange(v) {
      this.pageInfo.currentPage = v;
      this.activeDetailsHistory = this.pageHandle(
        this.tableData,
        this.pageInfo.currentPage,
        this.pageInfo.pageSize
      );
    },
    pageHandle(arr, currentPage, pageSize) {
      let _arr = [];
      currentPage = Number(currentPage);
      pageSize = Number(pageSize);
      for (
        let i = (currentPage - 1) * pageSize;
        i <= (currentPage - 1) * pageSize + pageSize - 1;
        i++
      ) {
        if (arr[i]) {
          _arr.push(JSON.parse(JSON.stringify(arr[i])));
        }
      }
      return _arr;
    }, // 分页函数
    sourceTypeSwitch(val) {
      let res = "未知";
      switch (val) {
        case 1:
          res = "规则创建";
          break;
        case 2:
          res = "结果保存";
          break;
      }
      return res;
    }, // 创建方式枚举
    isRoutineSwitch(val) {
      let res = "未知";
      switch (val) {
        case 1:
          res = "例行";
          break;
        case 0:
          res = "手动";
          break;
      }
      return res;
    }, // 更新方式枚举
    statusSwitch(val) {
      let res = "未知";
      switch (val) {
        case 0:
          res = "待执行";
          break;
        case 1:
          res = "成功";
          break;
        case 2:
          res = "失败";
          break;
        case 10:
          res = "执行中";
          break;
        case 11:
          res = "推迟执行";
          break;
      }
      return res;
    }, // 计算状态枚举
    classChoose(status) {
      let res = "未知";
      switch (status) {
        case 0:
          res = "info";
          break;
        case 1:
          res = "success";
          break;
        case 2:
          res = "danger";
          break;
        case 10:
          res = "running";
          break;
        case 11:
          res = "warning";
          break;
      }
      return res;
    }, // 计算状态类名枚举
    echartInit() {
      try {
        this.myChart.clear();
      } catch (err) {
        console.log("分群详情图形绘制", err);
      }
      let statusRes = "";
      let className = "";
      let xAxisData = [];
      let seriesData = [];
      this.tableData.map(_i => {
        xAxisData.push(this.time_change(_i.baseTime));
        _i.value = _i.userCount;
        _i.formatterTime = this.time_change(_i.baseTime);
        seriesData.push(_i);
      });
      let formatter = params => {
        switch (params[0].data.status) {
          case 0:
            className = "info";
            statusRes = "待执行";
            break;
          case 1:
            className = "success";
            statusRes = "成功";
            break;
          case 2:
            className = "danger";
            statusRes = "失败";
            break;
          case 10:
            className = "running";
            statusRes = "执行中";
            break;
          case 11:
            className = "warning";
            statusRes = "推迟执行";
            break;
        }
        let resHtml = `
          <div class='formatterBox'>
           <div class='formatterSta' :style="{color:'red'}">
              <i class='${className}'></i>
              计算状态：
              ${statusRes}
            </div> 
            <div class='formatterNum'>
              <span>计算基准时间：${params[0].data.formatterTime}</span>
              <span>${params[0].data.userCount}人</span>
            </div>
          </div>
        `;
        return resHtml;
      };
      let option = {
        backgroundColor: "#fff",
        grid: {
          left: "10%",
          top: "10%",
          right: "10%"
        },
        tooltip: {
          trigger: "axis",
          padding: [10, 10],
          backgroundColor: "#001529",
          textStyle: {
            color: "#fff"
          },
          extraCssText: "box-shadow: 1px 0 2px 0 rgba(163,163,163,0.5)",
          formatter: formatter
        },
        xAxis: {
          type: "category",
          data: xAxisData
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            itemStyle: {
              color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "#83bff6" },
                { offset: 0.5, color: "#188df0" },
                { offset: 1, color: "#188df0" }
              ])
            },
            emphasis: {
              itemStyle: {
                color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: "#2378f7" },
                  { offset: 0.7, color: "#2378f7" },
                  { offset: 1, color: "#83bff6" }
                ])
              }
            },
            data: seriesData,
            barWidth: 30, //柱图宽度
            type: "bar"
          }
        ]
      };
      this.myChart.setOption(option, true);
      this.myChart.resize();
      ElementResize.on(document.getElementById("userDetailsEchart"), () => {
        try {
          this.myChart.resize();
        } catch (err) {
          console.log(err);
        }
      });
    }, // 面板绘制函数
    createRules() {
      let obj = {};
      if (this.activeItem.id) {
        obj = JSON.parse(JSON.stringify(this.activeItem));
        obj.appId = this.appId;
        obj.jokerNum++;
      } else {
        obj = JSON.parse(JSON.stringify(this.activeDetails));
        obj.jokerNum = 1;
      }
      this.activeItem = obj;
    }, // 规则创建
    routerChange(path, obj) {
      // 如果是跳转
      if (path.indexOf("/userSelf") !== -1) {
        obj.productCode = JSON.parse(
          JSON.stringify(this.$store.state.global.appItem)
        ).productCode;
        obj.appId = JSON.parse(JSON.stringify(this.$store.state.global.appId));
        obj.taskType = "USERGROUPS";
        // obj.q = JSON.stringify(this.activeDetails);
        obj.q = JSON.stringify({
          filter: {
            conditions: [
              {
                field: "user." + this.activeDetails.name,
                function: "isTrue"
              }
            ]
          },
          measures: [
            {
              aggregator: "count",
              field: ""
            }
          ],
          from: "user_group",
          title: {
            name: this.activeDetails.cname,
            desc: "分群用户明细"
          }
        });
        obj.name = this.activeDetails.cname;
        let routeUrl = this.$router.resolve({
          path: path,
          query: obj
        });
        window.open(routeUrl.href, "_blank");
      } else {
        this.$router.push({
          path: path,
          query: obj
        });
      }
    }, // 路由跳转
    time_change(time) {
      let date = new Date(time); //获取一个时间对象
      let year = date.getFullYear(); // 获取完整的年份(4位,1970)
      let mon = date.getMonth() + 1; // 获取月份(0-11,0代表1月,用的时候记得加上1)
      let hour = date.getHours();
      let min = date.getMinutes();
      let sec = date.getSeconds();
      mon = mon < 10 ? "0" + mon : mon;
      hour = hour < 10 ? "0" + hour : hour;
      min = min < 10 ? "0" + min : min;
      let day = date.getDate(); // 获取日(1-31)
      day = day < 10 ? "0" + day : day;
      return year + "-" + mon + "-" + day + '-' + hour + '-' + min;
    } // 时间戳转换函数
  },
  created() {
    this.id = this.$route.query.id;
  },
  mounted() {
    this.myChart = this.$echarts.init(
      document.getElementById("userDetailsEchart"),
      "light"
    );
    this.query(); // 查询分群详情
    this.queryHistory(); // 查询历史详情
  },
  components: { createRules },
  computed: {
    appId() {
      return this.$store.state.global.appId;
    }
  }
};
</script>
<style lang="scss">
.formatterBox {
  width: 240px;
  font-size: 10px;
  .formatterSta {
    height: 30px;
    display: flex;
    font-size: 8px;
    align-items: center;
    color: #c0c4cc;
    i {
      margin: 0 4px 0 0;
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
    }
    .info {
      background: #909399;
    }
    .success {
      background: #13ce66;
    }
    .danger {
      background: #f56c6c;
    }
    .running {
      background: #007aff;
    }
    .warning {
      background: #e6a23c;
    }
  }
  .formatterNum {
    height: 30px;
    padding-left: 10px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
</style>
<style scoped lang="scss">
* {
  box-sizing: border-box;
}
.tanleOne {
  i {
    // font-size: 12px;
    margin: 0 6px;
    font-weight: 600;
  }
  .block {
    width: 2rem;
  }
  .time {
    color: #475669;
    font-size: 10px;
  }
  .info,
  .success,
  .danger,
  .running,
  .warning {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    opacity: 0.6;
  }
  .info {
    background: #909399;
  }
  .success {
    background: #13ce66;
  }
  .danger {
    background: #f56c6c;
  }
  .running {
    background: #007aff;
  }
  .warning {
    background: #e6a23c;
  }
}
.bigIcon {
  font-size: 0.26rem;
}
.crumbs_arr_box {
  cursor: pointer;
  span {
    margin-right: 6px;
  }
  span:nth-child(1):hover {
    color: #307ef2;
  }
  span:nth-child(2) {
  }
  span:nth-child(3) {
    font-weight: 400;
  }
}
.userDetails::-webkit-scrollbar {
  display: none;
}
.userDetails {
  width: 98%;
  margin: 0 auto;
  height: 98.6%;
  overflow-y: scroll;
  padding-bottom: 20px;
  .panelHeader {
    width: 98%;
    margin: 0 auto;
    border-left: 4px solid #04cb94;
    div {
      .head {
        font-size: 22px;
        color: #1f2d3d;
        font-weight: 600;
        padding-left: 10px;
        i {
          color: #99a9bf;
          font-size: 12px;
          font-weight: 400;
          margin: 0 6px;
        }
      }
      .txt {
        margin-left: 16px;
        font-size: 13px;
        color: #8492a6;
      }
      .run {
        i {
          margin: 0 6px 0 16px;
          font-size: 18px;
          font-weight: 600;
        }
        .green {
          color: #04cb94;
        }
        .err {
          color: #f56c6c;
        }
        .info {
          color: #909399;
        }
      }
      .circle {
        min-width: 3rem;
        border-radius: 12px;
        height: 0.6rem;
        margin: 0 16px 0 10px;
        background: rgba($color: #dcdfe6, $alpha: 0.3);
        text-indent: 10px;
        padding-left: 10px;
        .headCir {
          font-size: 22px;
          color: #1f2d3d;
          font-weight: 400;
          cursor: pointer;
          i {
            color: #99a9bf;
            font-size: 10px;
            font-style: normal;
            font-weight: 400;
            margin: 0 6px;
          }
          .point {
            display: inline-block;
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: #04cb94;
          }
          .pointgreen {
            background: #04cb94;
          }
          .pointerr {
            background: #f56c6c;
          }
          .el-icon-arrow-right {
            color: #99a9bf;
            font-weight: 600;
            margin-right: 18px;
          }
        }
      }
    }
    div:nth-child(1) {
      height: 0.6rem;
    }
    div:nth-child(2) {
      height: 0.6rem;
    }
    div:nth-child(3) {
      height: 1rem;
    }
  }
  section {
    width: 98%;
    margin: 30px auto;
    .flex_btw {
      span:nth-child(1) {
        text-indent: 10px;
      }
      height: 40px;
    }
    #userDetailsEchart {
      width: 100%;
      height: 6rem;
    }
  }
  footer {
    width: 98%;
    margin: 0px auto;
    .pageBox {
      width: 100%;
      justify-content: flex-end;
      align-items: center;
      margin: 10px auto 0;
    }
  }
}
</style>
